package com.cbh.amadeus.client.handler;

import com.cbh.amadeus.client.core.Subscriber;
import com.cbh.amadeus.client.utils.ChannelReference;
import com.cbh.amadeus.common.enums.MessageType;
import com.cbh.amadeus.common.protocol.AmadeusMessage;
import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ChenBiHui
 * @date 2025/4/25
 */
@Slf4j
public class RegisteredHandler extends SimpleChannelInboundHandler<AmadeusMessageWrap> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AmadeusMessageWrap msg) {
        MessageType type = MessageType.find(msg.getType());
        if (type == MessageType.REGISTERED) {
            Channel channel = ctx.channel();
            AmadeusMessage message = msg.getMessage();
            Subscriber.DEFAULT.execute(() -> {
                ChannelReference.set(channel, message.getProvider());
                log.info(
                        "===== [REGISTERED] Topic [{}] as [{}] register success =====",
                        message.getTopic(),
                        message.getPayload()
                );
            });
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
